package sm2_test2

import (
	"encoding/hex"
	"fmt"
	"github.com/tjfoc/gmsm/sm2"
	"math/big"
)

// 声明公钥和私钥（用实际的 SM2 密钥对替换）
const (
	publicKeyHex = "C3394E3A10CF948579FC8F033BE4DD0E1AFC04EA272C5D05F9F8D83E18CBEB087012459E06F0263C9344C71475854FF624C1CCFA72E39563083852ED23DF8498"
)

func Start() {

	// 解析公钥
	pubKey, err := parseSM2PublicKey(publicKeyHex)
	if err != nil {
		fmt.Println("Failed to parse public key:", err)
		return
	}

	// 假设的 userId
	userId := []byte("00000001")
	fmt.Println("userId:", hex.EncodeToString(userId))

	// 假设的 sourceData
	sourceData, err := hex.DecodeString("d9aa395a281d100cb37aded382249fb591bdc61c")
	if err != nil {
		fmt.Println("Failed to hex.DecodeString for sourceData:", err)
		return
	}

	signature, err := hex.DecodeString("4749d6fff3bad8969572fe5d4d9ec32d7c51e4faf168ed56f21594f497705bceff49dac250b21421921c85699806391b3378bc6f1eb22acb02a751880de70415")
	if err != nil {
		fmt.Println("Failed to hex.DecodeString for signature:", err)
		return
	}

	fmt.Println("Signature:", hex.EncodeToString(signature))

	// 验证签名
	isValid, err := VerifySignature(sourceData, userId, signature, pubKey)
	if err != nil {
		fmt.Println("Failed to verify signature:", err)
		return
	}

	if isValid {
		fmt.Println("Signature is valid.")
	} else {
		fmt.Println("Signature is invalid.")
	}
}

// parseSM2PublicKey 解析SM2公钥
func parseSM2PublicKey(publicKeyHex string) (*sm2.PublicKey, error) {
	publicKeyBytes, err := hex.DecodeString(publicKeyHex)
	if err != nil {
		return nil, err
	}
	x := new(big.Int).SetBytes(publicKeyBytes[:32])
	y := new(big.Int).SetBytes(publicKeyBytes[32:])
	pub := &sm2.PublicKey{
		Curve: sm2.P256Sm2(),
		X:     x,
		Y:     y,
	}
	return pub, nil
}

// VerifySignature 使用SM2算法验证签名
func VerifySignature(data, userId []byte, signature []byte, pubKey *sm2.PublicKey) (bool, error) {
	// 分离 R 和 S
	r := new(big.Int).SetBytes(signature[:32])
	s := new(big.Int).SetBytes(signature[32:])

	fmt.Printf("Signature R for verification: %x\n", r)
	fmt.Printf("Signature S for verification: %x\n", s)
	fmt.Printf("Data for verification: %x\n", data)

	// 验证签名
	return sm2.Sm2Verify(pubKey, data, userId, r, s), nil
}
